import { useUserStore } from '@/store/modules/user'
import axios, { AxiosRequestConfig } from 'axios'

/**
 * 请求方法
 */
const request = async (
  url: string,
  method: 'get' | 'post' | 'put' | 'delete',
  data: object,
  isUpload = false,
) => {
  // 客户状态管理
  const userStore = useUserStore()

  // axios调用参数
  const requestParam: AxiosRequestConfig = {
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 1000 * 60 * 10,
    withCredentials: true,
    method,
    url,
    headers: {},
  }

  // 接口请求参数
  if (data) {
    if (method === 'get') {
      requestParam['params'] = data
    } else {
      requestParam['data'] = data
    }
  }

  // 设置token
  requestParam.headers[userStore.row.tokenName] = userStore.row.tokenValue

  // 如果是上传文件的话就修改请求头
  if (isUpload === true) {
    requestParam.headers['Content-Type'] = 'multipart/form-data'
  }

  // 响应
  const res = await axios(requestParam)

  // 兼容旧版的返回
  if (res.status === 200) {
    return res
  }

  // 兼容旧版的返回
  return {
    data: {
      code: 40000,
      data: {},
      hasOtherCode: false,
      message: '',
      otherCodePrefix: null,
      success: false,
    },
  }
}

export default {
  get: (url: string, data: object) => {
    return request(url, 'get', data, false)
  },
  post: (url: string, data: object, isUpload = false) => {
    return request(url, 'post', data, isUpload)
  },
  put: (url: string, data: object, isUpload = false) => {
    return request(url, 'put', data, isUpload)
  },
  delete: (url: string, data: object) => {
    return request(url, 'delete', data, false)
  },
}
